package com.lsk.util;

import com.sun.deploy.net.URLEncoder;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by Administrator on 2017/7/20.
 */
public class UtilUrlEncode {

        private StringBuilder query = new StringBuilder();

        public synchronized void add(String name,String value){
            encode(name,value);
        }

        private synchronized void encode(String name, String value) {
            try {
                query.append(URLEncoder.encode(name,"UTF-8"));
                query.append('=');
                query.append(URLEncoder.encode(value,"UTF-8"));
                query.append('&');
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        public synchronized String getQuery(){
            query.deleteCharAt(query.length()-1);
            return query.toString();
        }

        public synchronized String decode() throws UnsupportedEncodingException{
            return URLDecoder.decode(getQuery(),"UTF-8");
        }

        public static void main(String[] args) {
            UtilUrlEncode test = new UtilUrlEncode();
            String url = "http://www.google.com?";
            test.add("a", "1/234");
            test.add("b", "ball");
            test.add("b", "ball");
            test.add("b", "ball");
            System.out.println(url+test.getQuery());
        }

    }

